<template>

  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input style="width: 20vw; font-size:15px;" v-model="data.title" placeholder="请输入标题查询" prefix-icon="Search"/>
      <el-button type="primary" style="margin-left: 10px; " @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 10px; " @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 10px">
      <el-button type="primary" style="" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="" @click="delBatch">批量删除</el-button>
    </div>
    <div class="card">
      <el-table :data="data.article" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="标题" prop="title"/>
        <el-table-column label="封面">
          <template #default="scope">
            <el-image v-if="scope.row.img" :preview-src-list="[scope.row.img]" preview-teleported :src="scope.row.img" style="display:block; width: 100px; height: 60px;"/>
          </template>
        </el-table-column>
        <el-table-column label="简介" prop="description" show-overflow-tooltip/>
        <el-table-column label="内容">
          <template #default="scope">
            <el-button type="primary" @click="view(scope.row.content)">查看内容</el-button>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" prop="time"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" circle @click="handleUpdate(scope.row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button type="danger" size="small" circle @click="del(scope.row.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:15px">
        <el-pagination
            @change="load"
            v-model:current-page="data.currentPage"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <el-dialog v-model="data.formVisible" title="文章信息" width="800" destroy-on-close>
      <el-form ref="formRef" :model="data.form" style="padding-right: 50px; padding-top:20px">
        <el-form-item label="封面" :label-width="80">
          <el-upload
              action="http://localhost:9090/files/upload"
              list-type="picture"
              :on-success="handleImgSuccess"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题" :label-width="80" prop="title">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="简介" :label-width="80" prop="description">
          <el-input type="textarea" rows="3" v-model="data.form.description" autocomplete="off" placeholder="请输入简介"/>
        </el-form-item>
        <el-form-item label="内容" :label-width="80">
          <div style="border: 1px solid #ccc; width: 100%;">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :default-config="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="data.viewVisible" title="文章内容" width="50%" :colse-on-click-modal="false" destroy-on-close>
      <div class="editor-content-view" style="padding: 20px" v-html="data.content"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.viewVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import {reactive, ref, onBeforeUnmount, shallowRef} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css';
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';
import '@/assets/view.css'


const data = reactive({
  title: null,
  name: null,
  currentPage: 1,
  pageSize: 5,
  total:0,
  article: [],
  formVisible: false,
  form: {},
  ids: [],
  viewVisible: false,
  content: 'null'
})

const baseUrl  = 'http://localhost:9090'
const editorRef = shallowRef()
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
editorConfig.MENU_CONF['uploadImage'] = {
  server: baseUrl + '/files/wang/upload',
  fieldName: 'file'
}
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor
}

const view = (content) => {
  data.content = content
  data.viewVisible = true
}

const handleImgSuccess = (res) => {
  console.log(res.data)
  data.form.img = res.data
}


const load = () => {
  request.get('/article/selectPage', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    console.log(res)
    data.article = res.data.list
    data.total = res.data.total
  })
}

const reset = () => {
  data.name = null
  load()
}

const handleAdd = () => {
  data.formVisible = true
  data.form = {}

}

const save = () => { //做两个操作 一个是新增，一个是标记
  data.form.id ? update() : add()
}

const add = () => {
  request.post('/article/add', data.form).then(res => { //没id
    if(res.code === '200'){
      ElMessage.success('保存成功');
      data.formVisible = false
      load()
    }else{
      ElMessage.error(res.msg);
    }

  })
}

const update = () => {
  request.put('/article/updateById', data.form).then(res => { //有id
    if(res.code === '200'){
      ElMessage.success('保存成功');
      data.formVisible = false
      load()
    }else{
      ElMessage.error(res.msg);
    }

  })
}

const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

const del = (id) =>{
  ElMessageBox.confirm('确定要删除吗？', '删除确认', {type: 'warning'}).then(() =>{
    request.delete('/article/deleteById/' +id).then(res => {
      if(res.code === '200'){
        ElMessage.success('删除成功');
        load()
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch()
}

const handleSelectionChange = (rows) => { //返回所有选中的行
  console.log(rows)
  //从选中的行数组里面去除所有航的id组成一个新数组
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

const delBatch = () => {
  if(data.ids.length === 0){
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('确定要删除吗？', '删除确认',  {type: 'warning'}).then(() =>{
    request.delete('/article/deleteBatch', {data: data.ids}).then(res => {
      if(res.code === '200'){
        ElMessage.success('删除成功');
        load()
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch()
}


load()
</script>